{% extends "index.html" %}


{% block title %}数据分析系统{% endblock %}

{% block css %}
<style>
    .dashboard-container {
        padding: 15px;
    }
    .stats-card {
        background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
        padding: 25px;
        border-radius: 12px;
        margin-bottom: 20px;
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
        border: 1px solid rgba(255, 255, 255, 0.8);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }
    
    /* 卡片顶部装饰条 */
    .stats-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 4px;
        background: linear-gradient(90deg, #4CAF50, #2196F3, #9C27B0);
        border-radius: 4px 4px 0 0;
    }
    
    /* 卡片悬停效果 */
    .stats-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
    }
    
    /* 卡片标题样式 */
    .stats-card h3 {
        font-size: 16px;
        color: #6c757d;
        margin-bottom: 15px;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        display: flex;
        align-items: center;
    }
    
    /* 卡片标题前的小圆点装饰 */
    .stats-card h3::before {
        content: '';
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: linear-gradient(135deg, #4CAF50, #2196F3);
        margin-right: 10px;
    }
    
    /* 卡片数值样式 */
    .stats-card .value {
        font-size: 32px;
        font-weight: 700;
        color: #2c3e50;
        margin: 10px 0;
        font-family: 'Arial', sans-serif;
        letter-spacing: -0.5px;
        position: relative;
        z-index: 1;
    }
    
    /* 卡片数值动画效果 */
    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    /* 为不同卡片设置不同的主色调 */
    .stats-card:nth-child(1) h3::before {
        background: #4CAF50;
    }
    .stats-card:nth-child(2) h3::before {
        background: #2196F3;
    }
    .stats-card:nth-child(3) h3::before {
        background: #FF9800;
    }
    .stats-card:nth-child(4) h3::before {
        background: #9C27B0;
    }
    .stats-card:nth-child(5) h3::before {
        background: #F44336;
    }
    .stats-card:nth-child(6) h3::before {
        background: #00BCD4;
    }
    .stats-card:nth-child(7) h3::before {
        background: #795548;
    }
    .stats-card:nth-child(8) h3::before {
        background: #607D8B;
    }
    .stats-card .trend {
        font-size: 12px;
        margin-top: 5px;
    }
    .stats-card .trend.up {
        color: #52c41a;
    }
    .stats-card .trend.down {
        color: #f5222d;
    }
    .chart-container {
        background: #fff;
        padding: 15px;
        border-radius: 4px;
        margin-bottom: 15px;
        box-shadow: 0 1px 3px rgba(0,0,0,.1);
        min-height: 300px;
    }
    .chart-title {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 15px;
        color: #333;
    }
    
    .sub-title {
        font-size: 14px;
        font-weight: bold;
        margin: 10px 0;
        color: #666;
    }
    .chart {
        width: 100%;
        height: 300px;
    }
    .table-container {
        background: #fff;
        padding: 15px;
        border-radius: 4px;
        margin-bottom: 15px;
        box-shadow: 0 1px 3px rgba(0,0,0,.1);
    }
    .filter-container {
        margin-bottom: 15px;
        padding: 15px;
        background: #fff;
        border-radius: 4px;
        box-shadow: 0 1px 3px rgba(0,0,0,.1);
    }
    .btn-primary {
        background-color: #1890ff;
        border-color: #1890ff;
    }
</style>
{% endblock %}

{% block body %}
<div class="dashboard-container">
    <!-- 筛选区域 -->
    <div class="filter-container">
        <div class="layui-form-item">
            <div class="layui-inline">
                <button class="layui-btn layui-btn-primary" id="btn-refresh">
                    <i class="layui-icon layui-icon-refresh"></i> 刷新数据
                </button>
            </div>
        </div>
    </div>

    <!-- 价格规则说明 -->
    <div style="background: #fff9e6; border-left: 4px solid #ff9800; padding: 10px 15px; margin-bottom: 15px; border-radius: 0 4px 4px 0;">
        <p style="color: #e65100; margin: 0;">脚本规则说明：每笔订单价格抽成20%，未完成订单将处以订单价格2倍的处罚。</p>
    </div>

    <!-- 统计卡片 -->
    <div class="layui-row">
        <div class="layui-col-md3">
            <div class="stats-card">
                <h3>总发单量</h3>
                <div class="value" id="total-orders">--</div>
            </div>
        </div>
        <div class="layui-col-md3">
            <div class="stats-card">
                <h3>今日发单量</h3>
                <div class="value" id="today-orders">--</div>
            </div>
        </div>
        <div class="layui-col-md3">
            <div class="stats-card">
                <h3>总完成收益</h3>
                <div class="value" id="total-profit">--</div>
            </div>
        </div>
        <div class="layui-col-md3">
            <div class="stats-card">
                <h3>订单完成率</h3>
                <div class="value" id="completion-rate">--</div>
            </div>
        </div>
        <div class="layui-col-md3">
            <div class="stats-card">
                <h3>今日收入</h3>
                <div class="value" id="today-income">--</div>
            </div>
        </div>
        <div class="layui-col-md3">
            <div class="stats-card">
                <h3>我的总投入成本</h3>
                <div class="value" id="total-investment">--</div>
            </div>
        </div>
        <div class="layui-col-md3">
            <div class="stats-card">
                <h3>代练通余额</h3>
                <div class="value" id="dailiantong-balance">--</div>
            </div>
        </div>
        <div class="layui-col-md3">
            <div class="stats-card">
                <h3>代练丸子余额</h3>
                <div class="value" id="dailianwanzi-balance">--</div>
            </div>
        </div>
        <div class="layui-col-md3">
            <div class="stats-card">
                <h3>已完结订单收益</h3>
                <div class="value" id="settled-orders-profit">--</div>
            </div>
        </div>
    </div>

    <!-- 图表区域 -->
    <div class="layui-row">
        <div class="layui-col-md6">
            <div class="chart-container">
                <div class="chart-title">订单状态分布</div>
                <div id="status-chart" class="chart"></div>
            </div>
        </div>
        <div class="layui-col-md6">
            <div class="chart-container">
                <div class="chart-title">7日订单趋势</div>
                <div id="trend-chart" class="chart"></div>
            </div>
        </div>
    </div>

    <div class="layui-row">
        <div class="layui-col-md6">
            <div class="chart-container">
                <div class="chart-title">利润分析</div>
                <div id="profit-chart" class="chart"></div>
            </div>
        </div>
        <div class="layui-col-md6">
            <div class="chart-container">
                <div class="chart-title">热门区服订单数量</div>
                <div id="server-chart" class="chart"></div>
            </div>
        </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
        <div class="chart-title">订单数据详情</div>
        <div class="layui-row">
            <div class="layui-col-md6">
                <div class="sub-title">订单状态详细数据</div>
                <table id="status-table" class="layui-table" lay-filter="status-table"></table>
            </div>
            <div class="layui-col-md6">
                <div class="sub-title">7日订单详细数据</div>
                <table id="trend-table" class="layui-table" lay-filter="trend-table"></table>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script src="/static/js/echarts.js"></script>
<script>
    // 全局变量
    var statusChart, trendChart, profitChart, serverChart;
    var statusTable, trendTable;
    
    // 初始化页面
    window.onload = function() {
        initCharts();
        initTables();
        bindEvents();
        loadData();
    }
    
    // 初始化图表
    function initCharts() {
        // 订单状态分布图（柱状图）
        statusChart = echarts.init(document.getElementById('status-chart'));
        statusChart.setOption({
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: [],
                axisLabel: {
                    interval: 0,
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value',
                name: '订单数量'
            },
            series: [{
                name: '订单数量',
                type: 'bar',
                data: [],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {offset: 0, color: '#83bff6'},
                        {offset: 0.5, color: '#188df0'},
                        {offset: 1, color: '#188df0'}
                    ])
                }
            }]
        });
        
        // 7日订单趋势图（柱状图）
        trendChart = echarts.init(document.getElementById('trend-chart'));
        trendChart.setOption({
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['订单数量', '利润']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: []
            },
            yAxis: [
                {
                    type: 'value',
                    name: '订单数量',
                    position: 'left'
                },
                {
                    type: 'value',
                    name: '利润',
                    position: 'right'
                }
            ],
            series: [
                {
                    name: '订单数量',
                    type: 'bar',
                    data: [],
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {offset: 0, color: '#83bff6'},
                            {offset: 0.5, color: '#188df0'},
                            {offset: 1, color: '#188df0'}
                        ])
                    }
                },
                {
                    name: '利润',
                    type: 'bar',
                    yAxisIndex: 1,
                    data: [],
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {offset: 0, color: '#73d13d'},
                            {offset: 0.5, color: '#36cfc9'},
                            {offset: 1, color: '#36cfc9'}
                        ])
                    }
                }
            ]
        });
        
        // 利润分析图（柱状图）
        profitChart = echarts.init(document.getElementById('profit-chart'));
        profitChart.setOption({
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['完成收益', '未完成收益']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: [],
                axisLabel: {
                    interval: 0,
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value',
                name: '金额'
            },
            series: [
                {
                    name: '完成收益',
                    type: 'bar',
                    data: []
                },
                {
                    name: '未完成收益',
                    type: 'bar',
                    data: []
                }
            ]
        });
        
        // 热门区服订单数量图（柱状图）
        serverChart = echarts.init(document.getElementById('server-chart'));
        serverChart.setOption({
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: [],
                axisLabel: {
                    interval: 0,
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value',
                name: '订单数量'
            },
            series: [
                {
                    name: '订单数量',
                    type: 'bar',
                    data: [],
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {offset: 0, color: '#83bff6'},
                            {offset: 0.5, color: '#188df0'},
                            {offset: 1, color: '#188df0'}
                        ])
                    }
                }
            ]
        });
        
        // 响应式调整
        window.addEventListener('resize', function() {
            statusChart.resize();
            trendChart.resize();
            profitChart.resize();
            serverChart.resize();
        });
    }
    
    // 初始化表格
    function initTables() {
        // 订单状态表格
        layui.use('table', function() {
            statusTable = layui.table;
            statusTable.render({
                elem: '#status-table',
                data: [],
                cols: [[
                    {field: 'code', title: '状态码', width: 80},
                    {field: 'name', title: '状态名称', width: 120},
                    {field: 'count', title: '订单数量', width: 100},
                    {field: 'percentage', title: '占比', width: 100, templet: function(d) {
                        return d.percentage + '%';
                    }}
                ]],
                page: false,
                height: 'full-20'
            });
        });
        
        // 7日订单趋势表格
        layui.use('table', function() {
            trendTable = layui.table;
            trendTable.render({
                elem: '#trend-table',
                data: [],
                cols: [[
                    {field: 'date', title: '日期', width: 120},
                    {field: 'orders_count', title: '订单数量', width: 120},
                    {field: 'profit', title: '利润', width: 120, templet: function(d) {
                        return d.profit.toFixed(2);
                    }}
                ]],
                page: false,
                height: 'full-20'
            });
        });
    }
    
    // 绑定事件
    function bindEvents() {
        // 刷新按钮点击事件
        window.BS_Layui_$('#btn-refresh').click(function() {
            loadData();
        });
    }
    
    // 加载数据
    function loadData() {
        // 显示加载动画
        layer.load(2);
        
        // 获取订单数据分析概览
        axios.get('/api/order_analytics/overview/')
            .then(function(response) {
                if (response.data.code === 0) {
                    var data = response.data.data;
                    
                    // 保存最新数据到全局变量
                    latestOverviewData = data;
                    
                    // 更新统计卡片
                    updateStatsCards(data);
                    
                    // 更新订单状态分布图表和表格
                    updateStatusData(data.status_distribution, data.total_orders);
                    
                    // 更新7日趋势图表和表格
                    updateTrendData(data.last_7_days_trend);
                    
                    // 更新热门区服图表
                    updateServerData(data.top_10_servers);
                } else {
                    layer.msg('获取数据分析失败：' + response.data.message, {icon: 2});
                }
            })
            .catch(function(error) {
                console.error('获取数据分析失败:', error);
                layer.msg('获取数据分析失败，请稍后重试', {icon: 2});
            });
        
        // 获取订单利润分析
        axios.get('/api/order_analytics/profit/')
            .then(function(response) {
                if (response.data.code === 0) {
                    var data = response.data.data;
                    
                    // 更新利润分析图表
                    updateProfitData(data.profit_by_status);
                } else {
                    layer.msg('获取利润分析失败：' + response.data.message, {icon: 2});
                }
            })
            .catch(function(error) {
                console.error('获取利润分析失败:', error);
                layer.msg('获取利润分析失败，请稍后重试', {icon: 2});
            });
            
        // 获取代练通余额
        getDailiantongBalance();
        
        // 获取代练丸子余额
        getDailianwanziBalance();
        
        // 设置加载完成定时器，确保所有请求都有时间完成
        setTimeout(function() {
            layer.closeAll('loading');
        }, 1500);
    }
    
    // 全局变量，用于存储最新的概览数据
    let latestOverviewData = null;

    // 更新统计卡片
    function updateStatsCards(data) {
        window.BS_Layui_$('#total-orders').text(data.total_orders);
        window.BS_Layui_$('#today-orders').text(data.today_orders);
        window.BS_Layui_$('#total-profit').text('¥' + data.total_completed_profit.toFixed(2));
        window.BS_Layui_$('#completion-rate').text(data.completion_rate + '%');
        window.BS_Layui_$('#settled-orders-profit').text('¥' + (data.settled_orders_profit || 0).toFixed(2));
        
        // 设置总投入成本（固定值）
        window.BS_Layui_$('#total-investment').text('¥1,182.25');
        
        // 今日已结算订单收入 - 使用data.settled_orders_profit直接显示
        // 这是根据当日的时间加上状态是9（已结算）的completed_profit订单完成收益全部加起来的值
        let todaySettledIncome = data.today_settled_profit || 0;
        
        // 确保结果为正数且保留两位小数
        todaySettledIncome = Math.max(0, Math.round(todaySettledIncome * 100) / 100);
        
        // 更新今日收入显示
        window.BS_Layui_$('#today-income').text('¥' + todaySettledIncome.toFixed(2));
    }
    
    // 获取代练通余额
    function getDailiantongBalance() {
        axios.get('/api/dailiantong/get_my_info/')
            .then(function(response) {
                if (response.data.code === 0) {
                    var sumBal = response.data.data.SumBal;
                    window.BS_Layui_$('#dailiantong-balance').text('¥' + sumBal.toFixed(2));
                } else {
                    console.error('获取代练通余额失败：' + response.data.message);
                    window.BS_Layui_$('#dailiantong-balance').text('获取失败');
                }
            })
            .catch(function(error) {
                console.error('获取代练通余额异常：', error);
                window.BS_Layui_$('#dailiantong-balance').text('获取异常');
            });
    }
    
    // 获取代练丸子余额
    function getDailianwanziBalance() {
        axios.get('/api/dailianwanzi/get_my_balance/')
            .then(function(response) {
                if (response.data.code === 0) {
                    var balance = parseFloat(response.data.data.balance);
                    var frozen = parseFloat(response.data.data.frozen);
                    var totalBalance = balance + frozen;
                    window.BS_Layui_$('#dailianwanzi-balance').text('¥' + totalBalance.toFixed(2));
                } else {
                    console.error('获取代练丸子余额失败：' + response.data.message);
                    window.BS_Layui_$('#dailianwanzi-balance').text('获取失败');
                }
            })
            .catch(function(error) {
                console.error('获取代练丸子余额异常：', error);
                window.BS_Layui_$('#dailianwanzi-balance').text('获取异常');
            });
    }
    
    // 更新订单状态数据
    function updateStatusData(statusDistribution, totalOrders) {
        // 准备图表数据
        var statusNames = [];
        var counts = [];
        var tableData = [];
        
        statusDistribution.forEach(function(item) {
            statusNames.push(item.name);
            counts.push(item.count);
            
            var percentage = totalOrders > 0 ? (item.count / totalOrders * 100).toFixed(2) : '0.00';
            tableData.push({
                code: item.code,
                name: item.name,
                count: item.count,
                percentage: percentage
            });
        });
        
        // 更新图表
        statusChart.setOption({
            xAxis: {
                data: statusNames
            },
            series: [{
                data: counts
            }]
        });
        
        // 更新表格
        layui.use('table', function() {
            statusTable.reload('status-table', {
                data: tableData
            });
        });
    }
    
    // 更新7日趋势数据
    function updateTrendData(trendData) {
        // 准备图表数据
        var dates = [];
        var orderCounts = [];
        var profits = [];
        
        trendData.forEach(function(item) {
            dates.push(item.date);
            orderCounts.push(item.orders_count);
            profits.push(item.profit);
        });
        
        // 更新图表
        trendChart.setOption({
            xAxis: {
                data: dates
            },
            series: [
                {
                    data: orderCounts
                },
                {
                    data: profits
                }
            ]
        });
        
        // 更新表格
        layui.use('table', function() {
            trendTable.reload('trend-table', {
                data: trendData
            });
        });
    }
    
    // 更新利润分析数据
    function updateProfitData(profitData) {
        // 准备图表数据
        var statusNames = [];
        var completedProfits = [];
        var uncompletedProfits = [];
        
        profitData.forEach(function(item) {
            statusNames.push(item.status_name);
            completedProfits.push(item.completed_profit);
            uncompletedProfits.push(item.uncompleted_profit);
        });
        
        // 更新图表
        profitChart.setOption({
            xAxis: {
                data: statusNames
            },
            series: [
                {
                    data: completedProfits
                },
                {
                    data: uncompletedProfits
                }
            ]
        });
    }
    
    // 更新热门区服数据
    function updateServerData(serverData) {
        // 准备图表数据
        var serverNames = [];
        var orderCounts = [];
        
        serverData.forEach(function(item) {
            for (var serverName in item) {
                serverNames.push(serverName);
                orderCounts.push(item[serverName]);
            }
        });
        
        // 更新图表
        serverChart.setOption({
            xAxis: {
                data: serverNames
            },
            series: [
                {
                    data: orderCounts
                }
            ]
        });
    }
</script>
{% endblock %}